package com.common.handler.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.common.exception.ErrorException;
import com.common.handler.HttpMethodHandler;
import com.common.resolve.ContentTypeResolve;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description:
 * @Date: 2025/7/3 22:20
 */
@Component
public class HttpPostMethodHandler extends HttpMethodHandler<JSONObject> {

    @Autowired
    private List<ContentTypeResolve> contentTypeResolves;

    private static final Logger logger = LoggerFactory.getLogger(HttpPostMethodHandler.class);

    @Override
    public boolean validateMethod(String method) {
        return HttpMethod.POST.name().equals(method);
    }

    @Override
    public JSONObject parseParams(ServletRequest servletRequest, ServletResponse servletResponse) {
        try  {
            ContentType contentType = resolveContentType(servletRequest.getContentType());
            if (ObjectUtils.isEmpty(contentType)) {
                logger.warn("-----------url:{}，请求类型解析异常【{}】-----------", ((HttpServletRequest) servletRequest).getRequestURI(), servletRequest.getContentType());
                return null;
            }
            for (ContentTypeResolve resolve : contentTypeResolves) {
                if (contentType.toString().equals(resolve.contentType().toString())) {
                    return resolve.resolve(servletRequest, servletResponse);
                }
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private ContentType resolveContentType(String contentType) {
        if (!StringUtils.hasText(contentType)) {
            return null;
        }
        if (contentType.contains(ContentType.MULTIPART.getValue())) {
            return ContentType.MULTIPART;
        }
        if (contentType.contains(ContentType.JSON.getValue())) {
            return ContentType.JSON;
        }
        return null;
    }
}
